package handlers

import (
	"github.com/gin-gonic/gin"
	"news-feed/models"
	"strconv"
)

func CommentCreate(c *gin.Context) {
	user_id, _ := strconv.Atoi(c.PostForm("user_id"))
	new_id, _ := strconv.Atoi(c.PostForm("new_id"))
	if user_id == 0 || new_id == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.Comment{
		UserID: user_id,
		NewID:  new_id,
	}
	tx := models.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "评论失败",
			})
			return
		}
	}()

	if err := tx.Error; err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}

	if err := tx.Commit().Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "评论失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "评论成功",
	})
	return

}
